/**
 * 配置
 * @this HitView:
 *
 * @flow
 * -------
 * @UI 配置 UI
 * -------
 * @require && @need
 *
 */
import React, { Component } from 'react'
import {
  StyleSheet,
  Keyboard,
  TouchableOpacity,
} from 'react-native'

import PropTypes from 'prop-types'
import ErrorNullInfo from './ErrorNullInfo'

export default class TipView extends Component {
  static propTypes = {
    onPress: PropTypes.func,
    doCloseTip: PropTypes.func,
    showTip: PropTypes.bool,
    subView: PropTypes.element,
  }

  static defaultProps = {
    doCloseTip: () => {},
    showTip: false,
    subView: null,
  }

  constructor(props) {
    super(props)
    this.state = {
      validateFail: false,
    }
    this.enable = false
    this.refFormInput = null

    this.unmount = false
    this.timerGetFoucus = null
  }

  componentWillUnmount() {
    this.unmount = true
    this.timerGetFoucus && clearTimeout(this.timerGetFoucus)
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { showTip } = nextProps
    this.setState({ validateFail: showTip })
  }

  getFocus = () => {
    const { formItemType } = this.props
    if (formItemType === 'input') {
      Keyboard.dismiss()
      this.timerGetFoucus = setTimeout(
        () => {
          if (this.unmount) return
          if (this.refFormInput && this.enable) {
            // console.log('this.refFormInput')
            if (this.refFormInput.focus) {
              // console.log('this.refFormInput.focus')
              this.refFormInput.focus()
            }
          }
        },
        10
      )
    } else {
      Keyboard.dismiss()
    }
  }

  onPress = () => {
    const { onPress, doCloseTip } = this.props
    const { validateFail } = this.state
    if (validateFail) {
      this.setState({ validateFail: false }, () => { this.enable = true })
      doCloseTip && doCloseTip()
    }
    this.getFocus()
    onPress && onPress()
  }

  renderDetail = () => {
    const { children, subView } = this.props
    const view = children || subView
    const childrenView = React.cloneElement(view, {
      ref: (e) => { this.refFormInput = e },
    })
    return childrenView
  }

  render() {
    let { activeOpacity, onPress, formItemType, ...other } = this.props
    const { validateFail } = this.state
    if (!activeOpacity && activeOpacity !== 0) activeOpacity = onPress ? 0.2 : 1
    return (
      <TouchableOpacity activeOpacity={activeOpacity}
        style={formItemType === 'select' ? styles.other : styles.container} onPress={() => { this.onPress() }} >
        {
          validateFail ? <ErrorNullInfo {...other} />
          : this.renderDetail()
        }
      </TouchableOpacity>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  other: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-end',
  },
})
